package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.bwie.domain.Goods;
import com.bwie.domain.Order;
import com.bwie.mapper.GoodsMapper;
import com.bwie.mapper.OrderMapper;
import com.bwie.utils.R;


import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.ActivityMapper;
import com.bwie.domain.Activity;
import com.bwie.service.ActivityService;

import javax.annotation.Resource;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService{

    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private OrderMapper orderMapper;


    @Override
    public R getActivityList() {
        List<Activity> activities = activityMapper.selectList(null);
//        this.redisTemplate.opsForValue().set("activity:", JSON.toJSONString(activities));
        return R.OK(activities);
    }

    @Override
    public R getGoods(Long id) {
        Goods goods = goodsMapper.selectById(id);
//        this.redisTemplate.opsForValue().set("goods:",JSON.toJSONString(goods));
        return R.OK(goods);
    }

    @Override
    public R execute(Long activityId, String userId) {
        //判断活动是否在进行中
        Activity activity = activityMapper.selectById(activityId);
        if(activity==null){
            return R.ERROR(404,"活动已经不存在或已经结束了！");
        }
        //效验并扣减库存
        Goods goods = goodsMapper.selectById(activity.getGoodsId());
        if(goods==null||goods.getAvailableStock()<=0){
            return R.ERROR(404,"商品已售空!");
        }
        //乐观锁更新库存
        int count = goodsMapper.reduceStockWithOptimisticLock(goods.getId(),goods.getVersion());
        if(count==0){
            return R.ERROR(404,"秒杀失败，请重新尝试！");
        }
        //创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setUserId(userId);
        order.setGoodsId(activity.getGoodsId());
        order.setActivityId(activityId);
        order.setOrderPrice(goods.getSeckillPrice());
        order.setOrderStatus(0); // 未支付
        order.setCreateTime(new Date());
        orderMapper.insert(order);
        return R.OK("秒杀成功，请尽快支付！");
    }
}
